package com.lujianfei.productprice.ui.order;

import android.content.DialogInterface;
import android.os.AsyncTask;
import android.view.View;

import java.util.List;

import androidx.appcompat.app.AlertDialog;

public class OrderPresenter implements OrderContract.Presenter {
    OrderContract.View view;
    OrderContract.Model model;

    public OrderPresenter(OrderContract.View view) {
        this.view = view;
        this.model = new OrderModel();
    }

    @Override
    public void loadData() {
        new AsyncTask<Void,List<OrderEntity>,List<OrderEntity>>(){

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                view.showLoading();
            }

            @Override
            protected List<OrderEntity> doInBackground(Void... voids) {
                return model.loadData();
            }

            @Override
            protected void onPostExecute(List<OrderEntity> orderEntities) {
                super.onPostExecute(orderEntities);
                view.setData(orderEntities);
                view.setTotalPrice(model.getTotalPrice());
                view.hideLoading();
            }
        }.execute();
    }

    @Override
    public void showLongClickDialog(final OrderEntity itemAtPosition) {
        final CharSequence[] items = new CharSequence[]{"删除","取消"};
        new AlertDialog.Builder(view.getContext()).setTitle("提示").setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                CharSequence item = items[which];
                if ("删除".equalsIgnoreCase(""+item)){
                    confirmDialog(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            model.delete(itemAtPosition);
                        }
                    });
                }
            }
        }).show();
    }

    private void confirmDialog(final View.OnClickListener onOkListener){
        new AlertDialog.Builder(view.getContext()).setTitle("提示").setMessage("确定要删除订单?")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (null!=onOkListener){
                            onOkListener.onClick(null);
                        }
                        loadData();
                    }
                }).setNegativeButton("取消",null)
                .show();
    }
}
